import { exec, spawn } from 'child_process';
import ora from 'ora';
import { readFileSync } from 'fs';
import chalk from 'chalk';
// 在 BuildCocos.ts 顶部添加路径处理
import path, { dirname, join, resolve } from 'path';
import { openFolder } from './Utils';
import { readJsonSync } from 'fs-extra';

// 获取项目根目录（根据当前文件位置推导）
const PROJECT_ROOT = resolve(__dirname, '../..');

export async function buildCocos(exeDir: string, projectPath: string, configPath: string, projectType: string) {
    const spinner = ora({
        text: "Loading...",
        spinner: "dots",
        color: "yellow"
    }).start();

    const child = spawn(
        exeDir,
        [
            '--project',
            projectPath,
            '--build',
            `logDest=./log.txt;configPath=${configPath}`
        ],
        { stdio: 'ignore' }
    );


    return new Promise((resolve, reject) => {
        child.on('error', (err) => console.error(`进程错误: ${err}`));
        child.on('close', (code) => {
            if (code != 36) {
                spinner.fail(`构建失败，请检查错误日志，返回码:${code}`);
                resolve(false)
                return
            }
            spinner.succeed(`${projectType}=>构建成功！`);

            let buildConfig = readJsonSync(configPath)
            let buildPath = path.join(buildConfig.buildPath.replace("project:", projectPath), buildConfig.outputName)
            openFolder(buildPath);
            resolve(true)
        });
    })
}

export async function buildRpk(name: string, buildOutputDir: string, release = false) {
    switch (name) {
        case "oppo-mini-game":
            await BuildOppoRpk(buildOutputDir, release)
            break;
        case "huawei-quick-game":
            await BuildHuaWeiRpk(buildOutputDir, release)
            break;
    }
    openFolder(path.join(buildOutputDir, "dist"));
}


async function BuildOppoRpk(buildOutputDir: string, release = false) {
    const spinner = ora({
        text: "Loading...",
        spinner: "dots",
        color: "yellow"
    }).start();
    let args = ["pack"]
    if (release)
        args.push("release")

    const child = spawn(
        "quickgame",
        args,
        {
            stdio: 'inherit',
            cwd: buildOutputDir,
            shell: true  // 确保使用shell解析
        }
    );


    return new Promise((resolve, reject) => {
        child.on('error', (err) => console.error(`进程错误: ${err}`));
        child.on('close', (code) => {
            if (code !== 0) {
                spinner.fail(`构建失败，请检查错误日志，返回码:${code}`);
                resolve(false)
                return
            }
            spinner.succeed(`构建成功！=>${buildOutputDir}/dist`);
            resolve(true)
        });
    })
}


async function BuildHuaWeiRpk(buildOutputDir: string, release = false) {
    const spinner = ora({
        text: "Loading...",
        spinner: "dots",
        color: "yellow"
    }).start();


    // 读取游戏配置文件示例
    const jsonData = JSON.parse(readFileSync(`${buildOutputDir}/manifest.json`, 'utf-8'));
    const toolDir = join(PROJECT_ROOT, 'signtool/package/index.js');
    // node {签名工具路径} {签名目录} {目标目录} {包名} {私钥} {证书}
    // node.\signtool\package\index.js.\build.\dist com.demo.\release\private.pem.\release\certificate.pem
    let args = [toolDir, `${buildOutputDir}`, `${buildOutputDir}/dist`, jsonData.name, `${buildOutputDir}/sign/debug/private.pem`, `${buildOutputDir}/sign/debug/certificate.pem`]
    if (release) {
        args = [toolDir, `${buildOutputDir}`, `${buildOutputDir}/dist`, jsonData.name, `${buildOutputDir}/sign/release/private.pem`, `${buildOutputDir}/sign/release/certificate.pem`]
    }
    const child = spawn(
        "node",
        args,
        {
            stdio: 'inherit',
            shell: true  // 确保使用shell解析
        }
    );


    return new Promise((resolve, reject) => {
        child.on('error', (err) => console.error(`进程错误: ${err}`));
        child.on('close', (code) => {
            if (code !== 0) {
                spinner.fail(`构建失败，请检查错误日志，返回码:${code}`);
                resolve(false)
                return
            }
            spinner.info(chalk.blueBright(`${buildOutputDir}/dist/${jsonData.name}.rpk`))
            spinner.succeed(`构建成功！`);

            resolve(true)
        });
    })
}